package com.order.service.Impl;

import com.common.VO.SysResult;
import com.common.domain.Order;
import com.common.domain.OrderItem;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.order.dao.OrderDao;
import com.order.exception.MsgException;
import com.order.service.CartService;
import com.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-25 10:09
 * @description
 * @copyright 2021
 */
@Service
public class OrderServiceImpl implements OrderService {
  @Autowired private OrderDao orderDao;

  @Autowired private CartService cartService;

  @Autowired private ObjectMapper mapper;

  @Override
  public void addOrder(Order order) {
    order.setOrderId(UUID.randomUUID().toString());
    order.setOrderTime(new Date());
    order.setOrderPaystatus(0);
    List<OrderItem> items = order.getOrderItems();
    List<String> productIds = new LinkedList<>();
    List<Integer> productNums = new LinkedList<>();
    for (OrderItem item : items) {
      productIds.add(item.getProductId());
      productNums.add(item.getNum());
    }
    try {
      SysResult result =
          cartService.getMoney(
              mapper.writeValueAsString(productIds),
              mapper.writeValueAsString(productNums),
              order.getUserId());

      if (result == null) {
        throw new MsgException(" 查询出错");
      }
      if (result.getStatus() == 200) {
        Double money = (Double) result.getData();
        if (Math.abs(money - order.getOrderMoney()) > 0.0001) {
          throw new MsgException("后台校验金额出错");
        }
        orderDao.addOrderAndItem(order);
      } else {
        Exception exception = (Exception) result.getData();
        if (exception == null) {
          throw new MsgException("exception为空指针");
        } else {
          throw new MsgException(exception.getMessage());
        }
      }
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
  }

  @Override
  public List<Order> queryOrder(String userId) {
    // TODO: 2021/6/25  先用userid查询orderid，再根据orderid查商品
    List<Order> orders = orderDao.selectOrder(new Order(null, null, null, null, null, userId));
    for (Order order : orders) {
      List<OrderItem> orderItems =
          orderDao.selectOrderItems(
              new OrderItem(null, order.getOrderId(), null, null, null, null, null));
      order.setOrderItems(orderItems);
    }
    return orders;
  }

  @Override
  public void deleteOrder(String orderId) {
    orderDao.deleteOrder(new Order(orderId, null, null, null, null, null));
    orderDao.deleteOrderItems(new Order(orderId, null, null, null, null, null));
  }
}
